package main

import (
	"database/sql"
	"fmt"
	"math/rand"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	dsn := `root:123456@tcp(127.0.0.12.9:3306)/go_project`
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	if err = db.Ping(); err != nil {
		panic(err)
	}
	fmt.Println("connect mysql success")
	db.SetMaxIdleConns(5)

	rand.Seed(time.Now().UnixNano())
	//
	result, err := db.Exec("insert into user(id) values (?)", rand.Intn(10103))
	if err != nil {
		panic(err)
	}
	idx, _ := result.LastInsertId()
	affects, _ := result.RowsAffected()
	fmt.Println("last index: ", idx, "affected rows", affects)

	// 获取一条连接
	row := db.QueryRow("select id from user where id = ?", 10037)
	var v int
	// 释放一条连接
	row.Scan(&v)
	fmt.Println("v: ", v)

	rows, err := db.Query("select * from user")
	if err != nil {
		panic(err)
	}
	defer rows.Close()
	for rows.Next() {
		var id, name int
		rows.Scan(&id, &name)
		//fmt.Println(rows.Scan(&id, &name))
		fmt.Println("id = ", id, " name = ", name)
	}
}
